package cn.iocoder.mall.statistics.application.controller.order;

import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.TimeUtils;
import cn.iocoder.mall.order.api.OrderService;
import cn.iocoder.mall.order.api.bo.OrderBO;
import cn.iocoder.mall.order.api.vo.OrdersVO;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import cn.iocoder.mall.user.api.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: LL
 * @Date: 2019/12/13 15:14
 */
@RestController
@RequestMapping("/orderChart")
@Slf4j
public class OrderStatisticsController {

    @Reference(validation = "true",version = "${dubbo.consumer.UserService.version}")
    UserService userService;

    @Reference(validation = "true",version = "${dubbo.consumer.OrderService.version}")
    OrderService orderService;

    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    ShopService shopService;

    /**
     * 根据订单状态查询数据(图表展示)
     * @return
     */
    @GetMapping("/pieChart")
    public CommonResult getOrderDataPieChart(String startTime, String endTime){
        Map<String,Integer> map = new HashMap();
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int count4 = 0;
//        String id = JwtUtil.getUserIdByToken();
        List<ShopDTO> data = shopService.getListOfStores("0a4d2dcd8c9b68a33235fafd3dc1e362").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());

        CommonResult<List<OrderBO>> ordersForChart = orderService.getOrdersForChart(shopIds, startTime, endTime);

        List<OrderBO> orderList = ordersForChart.getData();

        for(int i = 0; i < orderList.size(); i++){

            if (orderList.get(i).getStatus() == 1){
                count1++;
                map.put("待付款",count1);
            }else if(orderList.get(i).getStatus() == 2){
                count2++;
                map.put("待发货",count2);
            }else if(orderList.get(i).getStatus() == 3){
                count3++;
                map.put("待收货",count3);
            }else if(orderList.get(i).getStatus() == 4){
                count4++;
                map.put("已完成",count4);
            }
        }
        return CommonResult.success(map);
    }

    /**
     * 每周订单转化率
     * @return
     */
    @GetMapping("/getOrderConversionRate")
    public CommonResult getOrderConversionRate(){
        OrdersVO vo = new OrdersVO();
        int count = 0;
        Map resultMap = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("YY/MM/dd");
        double orderConversionRate ;
//        String id = JwtUtil.getUserIdByToken();
        List<ShopDTO> data = shopService.getListOfStores("0a4d2dcd8c9b68a33235fafd3dc1e362").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        Map<String, String> map = TimeUtils.getLastTimeInterval(new Date());
        vo.setStartCreateTime(map.get("lastStart"));
        vo.setEndCreateTime(map.get("lastEnd"));

        CommonResult<Map<Object, Object>> reMap = orderService.getOrderConversionRate(shopIds, vo);

        OrdersVO ordersVO = (OrdersVO) reMap.getData().get("ordersVO");

        List<OrderBO> orderBOList = (List<OrderBO>) reMap.getData().get("orderBOList");

        if(ordersVO.getTotalOrders() > 0 && ordersVO.getCompletedOrders() > 0){
            //计算订单转化率
            orderConversionRate = (ordersVO.getCompletedOrders() / ordersVO.getTotalOrders()) * 100;
            //转化率四舍五入
            ordersVO.setOrderConversionRate(new BigDecimal(orderConversionRate).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        }

        for (OrderBO orderBO : orderBOList) {
            count++;
            if (resultMap.containsKey(sdf.format(orderBO.getCreateTime()))) {
                resultMap.put(sdf.format(orderBO.getCreateTime()), count++);
            } else {
                resultMap.put(sdf.format(orderBO.getCreateTime()), count);
            }
        }
        resultMap.put("ordersVO",ordersVO);
        return CommonResult.success(resultMap);
    }

    /**
     * 订单月核销笔数
     * @return
     */
    @GetMapping("/getOrderCancellationData")
    public CommonResult getOrderCancellationData(){
        int orderCancellationDataCount ;
//        String id = JwtUtil.getUserIdByToken();
        // 根据商户ID获取店员ID
        List<String> clerkIds = userService.getClerkIdsBySellerId("6f48d9393c58eb6bdfec235a93041b9b");

        Long monthStartTime = TimeUtils.getMonthStartTime(System.currentTimeMillis(), "GMT+8:00");
        //当月开始时间
        String startTime = TimeUtils.timestampToStr(monthStartTime);
        Long monthEndTime = TimeUtils.getMonthEndTime(System.currentTimeMillis(), "GMT+8:00");
        //当月结束时间
        String endTime = TimeUtils.timestampToStr(monthEndTime);

        if(clerkIds != null && clerkIds.size() > 0){
            CommonResult<Integer> orderCancellationData = orderService.getOrderCancellationData(clerkIds, startTime, endTime);
            orderCancellationDataCount = orderCancellationData.getData();
        }else {
            return CommonResult.error("没有核销记录");
        }
        return CommonResult.success(orderCancellationDataCount);
    }
}

